package com.common.dingding.realm;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

@Component
public class JwtRealm extends AuthorizingRealm {

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 实现认证逻辑
        String username = (String) token.getPrincipal();
        // 这里应该从数据库或缓存中查询用户信息
        // 例如：User user = userService.findByUsername(username);
        // if (user == null) {
        //     throw new UnknownAccountException("用户不存在");
        // }
        System.out.println("JwtRealm.doGetAuthenticationInfo 被调用");
        return new SimpleAuthenticationInfo(username, "password", getName());
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 实现授权逻辑
        System.out.println("JwtRealm.doGetAuthorizationInfo 被调用");
        String username = (String) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Set<String> roles = new HashSet<>();
        // 添加角色
        roles.add("user");
        authorizationInfo.setRoles(roles);
        return authorizationInfo;
    }
}